package com.af.security.configurer;

import com.af.security.auth.login.service.AfUserDetailsService;
import com.af.security.auth.phone.PhoneSecurityConfigurerAdapter;
import com.af.security.auth.util.handler.*;
import com.af.security.auth.util.session.AfInvalidSessionStrategy;
import com.af.security.auth.util.session.AfSessionExpiredStrategy;
import com.af.security.jwt.filter.JwtAuthenticationTokenFilter;
import com.af.security.jwt.token.JwtTokenService;
import com.af.security.jwt.token.X3JwtTokenService;
import com.af.security.property.LdapProperties;
import com.af.security.property.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.session.HttpSessionEventPublisher;

/**
 * @author : zhenyun.su
 * @since : 2019/6/18
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class AfWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private LdapProperties ldapProperties;
    @Autowired
    private AfUserDetailsService afUserDetailsService;
    @Autowired
    private AfNotLoginHandler notLoginHandler;
    @Autowired
    private AfAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private AfLogoutSuccessHandler logoutSuccessHandler;
    @Autowired
    private AfAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AfAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private AfInvalidSessionStrategy invalidSessionStrategy;
    @Autowired
    private AfSessionExpiredStrategy sessionExpiredStrategy;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(afUserDetailsService);

//        auth.authenticationProvider(authenticationProvider());

        if (ldapProperties.getEnabled()) {
            auth.ldapAuthentication()
                    .userSearchFilter(ldapProperties.getUserSearchFilter())
                    .contextSource()
                    .url(ldapProperties.getUrl())
                    .managerDn(ldapProperties.getManagerDn())
                    .managerPassword(ldapProperties.getManagerPassword());
        }
//        super.configure(auth);
    }

//    @Bean
//    public AuthenticationProvider authenticationProvider() {
//        LdapAuthenticationProviderConfigurer configurer = new LdapAuthenticationProviderConfigurer();
//
//
//        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider();
//
//        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
//        daoAuthenticationProvider.setUserDetailsService(szyUserDetailsService);
//        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
//        return daoAuthenticationProvider;
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登入&登出配置
        http.formLogin()
                .loginPage(securityProperties.getLoginPage())
                .loginProcessingUrl("/perform_login")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .and().httpBasic().authenticationEntryPoint(notLoginHandler)
                .and()
                .logout()
                .logoutUrl("/perform_logout")
                .logoutSuccessHandler(logoutSuccessHandler)
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(false)
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler);
        //记住我服务配置
        http.rememberMe()
                .key(securityProperties.getRememberMeKey())
                .tokenValiditySeconds(securityProperties.getRememberMeTokenExpired());
        //认证&授权配置
        http.authorizeRequests()
                .antMatchers(securityProperties.getLoginPage()).permitAll()
                .antMatchers(securityProperties.getPermitUrls()).permitAll()
                .antMatchers(securityProperties.getAuthUrls()).authenticated()
                .antMatchers("/account/password/reset").hasAuthority("RESET_PASSWORD_PRIVILEGE")
                .anyRequest().authenticated()
                .and().cors()
                .and().csrf().disable();
        //请求Headers设置
        http.headers().httpStrictTransportSecurity()
                .and().cacheControl()
                .and().frameOptions().disable().and();

        //会话管理设置
        http.sessionManagement(sessionMgt -> {
            sessionMgt.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .invalidSessionStrategy(invalidSessionStrategy)
                    .maximumSessions(securityProperties.getSessionMaxCount())
                    .maxSessionsPreventsLogin(securityProperties.getSessionPreventLoginPolicy())
                    .expiredSessionStrategy(sessionExpiredStrategy);
        });
        //添加手机验证码身份认证适配器
        http.apply(phoneSecurityConfigurerAdapter());
        //添加过滤器
//        http.addFilterBefore(smsCodeValidateFilter(), UsernamePasswordAuthenticationFilter.class));
        http.addFilter(new JwtAuthenticationTokenFilter(authenticationManager, jwtTokenService(), authenticationSuccessHandler, authenticationFailureHandler));

    }

    @Override
    public void configure(final WebSecurity web) throws Exception {
        web.ignoring().antMatchers(securityProperties.getIgnoreUrls());
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    private PhoneSecurityConfigurerAdapter phoneSecurityConfigurerAdapter() {
        return new PhoneSecurityConfigurerAdapter(authenticationSuccessHandler, authenticationFailureHandler);
    }

    @Bean
    public JwtTokenService jwtTokenService(){
        return new X3JwtTokenService();
    }
}
